//login.js
const app = getApp()

import WxValidate from '../../../utils/WxValidate.js';
import http from "../../../utils/http.js";
const {
  $Message
} = require('../../../component/iview/base/index');
Page({
  data: {
    remind: '加载中',
    help_status: false,
    userid_focus: false,
    passwd_focus: false,
    userid: '',
    passwd: '',
    angle: 0,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onReady: function() {
    var _this = this;
    setTimeout(function() {
      _this.setData({
        remind: ''
      });
    }, 1000);
    wx.onAccelerometerChange(function(res) {
      var angle = -(res.x * 30).toFixed(1);
      if (angle > 14) {
        angle = 14;
      } else if (angle < -14) {
        angle = -14;
      }
      if (_this.data.angle !== angle) {
        _this.setData({
          angle: angle
        });
      }
    });
  },
  onLoad: function() {
    wx.getUserInfo({
      success: res => {
        this.setUserInfo(res);
      },
      fail: res => {
        //未授权，不能使用
        // wx.switchTab({
        //   url: '/pages/index/index'
        // });
      }
    })
  },
  bindGetUserInfo: function(e) {
    if (e.detail.errMsg == "getUserInfo:ok") {
      //说明用户点击了确定授权
      this.setUserInfo(e.detail);
    } else {

      wx.switchTab({
        url: '/pages/index/index',
        success: res => {
          var page = getCurrentPages().pop();
          page.getNotice();
        }
      });

    }
  },
  setUserInfo: function(detail) {
    //到这里说明用户已经授权允许获取用户信息了。可以在这里绑定用户信息

    app.globalData.userInfo = detail.userInfo;
    wx.setStorageSync("wxUser", detail.userInfo);
    this.setData({
      userInfo: detail.userInfo,
      hasUserInfo: true
    });
    wx.login({
      success: res => {
        if (res.errMsg == "login:ok") {
          let data = {
            wxLogin: 'true', //使用微信登录标志，不需要再输入用户名密码，直接可通过微信登录
            iv: detail.iv, //公钥
            encryptedData: detail.encryptedData, //加密的信息
            jsCode: res.code //通过wx.login获取的jsCode
          };
          this.doLogin(data);
        }
      }
    });
  },
  /**
   * @param data
   * @param callback 
   * @param manualFlag true代表用户手动登录 空或者false代表自动登录
   */
  doLogin: function(data, callback, manualFlag) {
    //  ，如果无法登录，则显示登录界面
    wx.showLoading({
      title: '处理中...',
      mask: true
    })
    wx.request({
      url: http.apiUrl + "/login", //自己的后台登录方法（即cortroller层的登录方法地址）
      method: 'POST',
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      success: function(res) {
        wx.hideLoading();

        if (res.data.code == 200) {
          //说明登录成功
          wx.setStorageSync("sessionid", res.header["Set-Cookie"].split(";")[0]);
          http.request({
            url: '/member/findMemberUserInfo',
            data: {},
            success: (result) => {
              wx.setStorageSync("userInfo", result);
              app.globalData.isBindWx = true;
               //重新登录时清除字典
              const { deleteDicts } = require('../../../utils/dict.js')
              deleteDicts();
              wx.switchTab({
                url: '/pages/index/index',
                success: res => {
                  var page = getCurrentPages().pop();
                  page.getNotice();
                }
              });
            }

          });

          //登录成功后调用回调函数，主要是为了绑定小程序和登录的帐号
          if (callback) {
            callback();
          }

        } else if (res.data.code == 400 && manualFlag) {
          //登录异常的提示
          $Message({
            content: res.data.message,
            type: 'error'
          });
          // wx.showToast({
          //   title: res.data.message,//提示文字
          //   duration: 2000,//显示时长
          //   mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
          //   icon: 'none', //图标，支持"success"、"loading"  

          // })


        } else {

        }
      },
      fail: function() {
        wx.hideLoading()
      }
    });
  },
  bindWxId: function() {
    //将微信标识和当前帐号绑定
    wx.getUserInfo({
      success: detail => {
        wx.login({
          success: res => {
            if (res.errMsg == "login:ok") {
              http.request({
                url: '/common/bindWxId',
                data: {
                  iv: detail.iv, //公钥
                  encryptedData: detail.encryptedData, //加密的信息
                  jsCode: res.code //通过wx.login获取的jsCode
                },
                success: (data) => {

                }
              });
            }
          }
        });
      }
    });
  },
  btnLogin: function() {
    // const params = e.detail.value;
    var data = {};
    var username = this.data.userid;
    var password = this.data.passwd;
    data.username = username;
    data.password = password;
    //校验表单
    let msg = null;
    if (username == null || username == "") {
      msg = "用户名不能为空";
    } else if (password == null || password == "") {
      msg = "密码不能为空";
    }
    if (msg != null) {
      $Message({
        content: msg,
        type: 'error'
      });
      return false;
    }

    this.doLogin(data, this.bindWxId, true);
  },



  useridInput: function(e) {
    this.setData({
      userid: e.detail.value
    });
    if (e.detail.value.length >= 20) {
      wx.hideKeyboard();
    }
  },
  passwdInput: function(e) {
    this.setData({
      passwd: e.detail.value
    });
  },
  inputFocus: function(e) {
    if (e.target.id == 'userid') {
      this.setData({
        'userid_focus': true
      });
    } else if (e.target.id == 'passwd') {
      this.setData({
        'passwd_focus': true
      });
    }
  },
  inputBlur: function(e) {
    if (e.target.id == 'userid') {
      this.setData({
        'userid_focus': false
      });
    } else if (e.target.id == 'passwd') {
      this.setData({
        'passwd_focus': false
      });
    }
  },
  tapHelp: function(e) {
    if (e.target.id == 'help') {
      this.hideHelp();
    }
  },
  showHelp: function(e) {
    this.setData({
      'help_status': true
    });
  },
  hideHelp: function(e) {
    this.setData({
      'help_status': false
    });
  }
});